package org.erepublik.company.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.erepublik.company.ECountry;
import org.erepublik.company.generated.monetarymarket.MMOfferT;
import org.erepublik.company.generated.monetarymarket.MMOffersT;
import org.erepublik.company.utils.WebpageReader;
import org.erepublik.company.xml.XMLParsersers;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Klasa skanuje api erepublik.com i pozyskuje informacje o biezacym kursie (w
 * stosunku do zlota).
 * 
 * Api skanowane jest tylko raz, po nastepnym pobraniu Wyniki sa kaszowane.
 * UWAGA! Przy kazdym skanie wyniki sa zapisywane do JSONa na dysk!
 * 
 * @author Kacper Gorski 'Railman' railman85@gmail.com
 */
public class InternetExchangeRateService implements IExchangeRateService {

    private HashMap<ECountry, Double> exchangeRates = null; // obiekt, w ktorym
                                                            // sa skaszowane
                                                            // wartosci walut
    private HashMap<ECountry, Double> exchangeRatesReverted = null; // obiekt, w
                                                                    // ktorym sa
                                                                    // skaszowane
                                                                    // wartosci
                                                                    // walut

    public HashMap<ECountry, Double> getExchangeRates() throws Exception {

        if (exchangeRates != null)
            return exchangeRates;

        ECountry[] countries = ECountry.values();
        HashMap<ECountry, Double> exchangeRates = new HashMap<ECountry, Double>();
        for (int i = 0; i < countries.length; i++) {
            System.out.println("skanuje kurs waluty dla " + countries[i]);
//            InputStream stream = WebpageReader.getStreamToIrl("http://api.erepublik.com/v2/feeds/exchange/"
//                    + countries[i].getCurrencyName() + "/GOLD");
            
            InputStream stream = WebpageReader.getStreamToIrl("http://api.erepublik.com/v2/feeds/exchange/GOLD/"
                    + countries[i].getCurrencyName());
            
            MMOffersT offers = XMLParsersers.parseMonetaryMarket(stream);
            List<MMOfferT> offerList = offers.getOffer();
            if (offerList == null || offerList.size() == 0)
                exchangeRates.put(countries[i], 0d);
            else {
                double exchangeRate = Math.ceil( (1.0/offerList.get(0).getExchangeRate()) * 1000.0d) / 1000.0d;
                exchangeRates.put(countries[i], exchangeRate);
            }
        }
        this.exchangeRates = exchangeRates;
        saveToJSONFile();

        return exchangeRates;
    }

    public HashMap<ECountry, Double> getExchangeRatesReverted() throws Exception {

        if (exchangeRatesReverted != null)
            return exchangeRatesReverted;

        ECountry[] countries = ECountry.values();
        HashMap<ECountry, Double> exchangeRates = new HashMap<ECountry, Double>();
        for (int i = 0; i < countries.length; i++) {
            System.out.println("skanuje kurs waluty dla " + countries[i]);
            InputStream stream = WebpageReader.getStreamToIrl("http://api.erepublik.com/v2/feeds/exchange/GOLD/"
                    + countries[i].getCurrencyName());
            MMOffersT offers = XMLParsersers.parseMonetaryMarket(stream);
            List<MMOfferT> offerList = offers.getOffer();
            if (offerList == null || offerList.size() == 0)
                exchangeRates.put(countries[i], 0d);
            else {
                double exchangeRate = Math.round(offerList.get(0).getExchangeRate() * 1000.0d) / 1000.0d;
                exchangeRates.put(countries[i], exchangeRate);
            }
        }
        this.exchangeRatesReverted = exchangeRates;

        return exchangeRates;
    }

    private void saveToJSONFile() {
        try {
            String urlToDirectory = JSONExchangeRateService.databasePath;
            File file = new File(urlToDirectory + "/" + new Date().getTime() + "-currency.json");
            file.createNewFile();
            BufferedWriter out = null;

            out = new BufferedWriter(new FileWriter(file.getAbsolutePath()));

            JSONObject json = new JSONObject();
            ECountry[] countries = ECountry.values();
            for (ECountry country : countries) {
                json.put(country.toString(), exchangeRates.get(country));
            }
            out.write(json.toString());
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
